<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<script type="text/javascript" src="${pageContext.request.contextPath}/lib/geoxml3.js"></script>
<script type="text/javascript"
        src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false&libraries=geometry">
</script>
<script type="text/javascript">
var map;
var geoData = new Object();
var count = 0;
var color = '';
var userRole = '<s:property  value="user.getRole().getId()"/>';
// Create a meausure object to store our markers, MVCArrays, lines and polygons
var measure = {
    mvcLine: new google.maps.MVCArray(),
    mvcPolygon: new google.maps.MVCArray(),
    mvcMarkers: new google.maps.MVCArray(),
    line: null,
    polygon: null
};

$(document).ready(function () {
    $('#kmlFile').hide();
    // $('#map').hide();
    displayKmlFromList();

});


//Display Interest Map
function displayKmlFromList() {

    $('#kmlFile').show();
    $('#map').show();
    var srilanka = new google.maps.LatLng(6.90262729, 79.92753258);
    var mapOptions = {
        zoom:      8,
        center:    srilanka,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        draggableCursor: "crosshair"
    };
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

    var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});

    for (var prop in geoData) {
        var mapData = geoData[prop];
        var kmlString = mapData.kmlString
        var kmlReferenceNumber = mapData.referenceNumber;
        var middlePoint = mapData.kmlMiddlePoint;
        var landArea = mapData.kmlLandArea
        var organizationName = mapData.landName;
        //var polyColor =  mapData.polyColor;
        var polyColor = getRandomColor();
        //var polyColor = mapData.colorCode;
        var lineColor = 64000000;
        //alert("50"+polyColor);

        var kml = "<kml>" + "<Document> <Style id=\"polyColorMap\" >" + " <LineStyle><color>" + lineColor + "</color><width>2.0</width></LineStyle> " +
                " <PolyStyle> <color>" + polyColor + "</color> </PolyStyle> <IconStyle><color>" + lineColor + "</color><scale>.500</scale></IconStyle></Style>" +
                "<Placemark>" +
                " <name>" + kmlReferenceNumber + "</name><description>" + organizationName + "</description><styleUrl>#polyColorMap</styleUrl><Polygon><extrude>1</extrude> " +
                " <altitudeMode>relativeToGround</altitudeMode><outerBoundaryIs><LinearRing><coordinates>" + kmlString + " </coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>" +
                "<Placemark><name>" + kmlReferenceNumber + "</name><description>" + organizationName + "</description><Point><coordinates>" + middlePoint + "</coordinates>" +
                "<referenceNo>" + kmlReferenceNumber + "</referenceNo></Point></Placemark></Document></kml>";

        geoXml.parseKmlString(kml);

    }

    google.maps.event.addListener(map, "click", function(evt) {
        // When the map is clicked, pass the LatLng obect to the measureAdd function
        measureAdd(evt.latLng);
    });

    changeHectareKml();
    measureReset();
    //}
}

function viewUserCreteArea(userArea) {

    var he = 0,ac = 0,ro = 0,pe = 0,temp = 0;
    var cont = 2.47105381467;
    he = userArea / 10000;

    if (1 > he > 0) {
        he = parseFloat(he);
    }
    ac = Math.floor(he * cont);
    temp = (he * cont - ac) * 4;
    ro = Math.floor(temp);
    temp = (temp - ro) * 40;
    pe = temp.toFixed(4);
    $("#useracreId").text(ac);
    $("#userroodsId").text(ro);
    $("#userperchesId").text(pe);
    $("#userhectareId").text(he.toFixed(4));
}



function measureAdd(latLng) {
    // Add a draggable marker to the map where the user clicked
    var marker = new google.maps.Marker({
        map: map,
        position: latLng,
        draggable: true,
        raiseOnDrag: false,
        title: "Drag me to change shape",
        icon: new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5))
    });

    // Add this LatLng to our line and polygon MVCArrays
    // Objects added to these MVCArrays automatically update the line and polygon shapes on the map
    measure.mvcLine.push(latLng);
    measure.mvcPolygon.push(latLng);

    // Push this marker to an MVCArray
    // This way later we can loop through the array and remove them when measuring is done
    measure.mvcMarkers.push(marker);

    // Get the index position of the LatLng we just pushed into the MVCArray
    // We'll need this later to update the MVCArray if the user moves the measure vertexes
    var latLngIndex = measure.mvcLine.getLength() - 1;

    // When the user mouses over the measure vertex markers, change shape and color to make it obvious they can be moved
    google.maps.event.addListener(marker, "mouseover", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(15, 15), new google.maps.Point(0, 0), new google.maps.Point(8, 8)));
    });

    // Change back to the default marker when the user mouses out
    google.maps.event.addListener(marker, "mouseout", function() {
        marker.setIcon(new google.maps.MarkerImage("${pageContext.request.contextPath}/images/measure-vertex.png", new google.maps.Size(9, 9), new google.maps.Point(0, 0), new google.maps.Point(5, 5)));
    });

    // When the measure vertex markers are dragged, update the geometry of the line and polygon by resetting the
    //     LatLng at this position
    google.maps.event.addListener(marker, "drag", function(evt) {
        measure.mvcLine.setAt(latLngIndex, evt.latLng);
        measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
    });

    // When dragging has ended and there is more than one vertex, measure length, area.
    google.maps.event.addListener(marker, "dragend", function() {
        if (measure.mvcLine.getLength() > 1) {
            measureCalc();
        }
    });

    // If there is more than one vertex on the line
    if (measure.mvcLine.getLength() > 1) {

        // If the line hasn't been created yet
        if (!measure.line) {

            // Create the line (google.maps.Polyline)
            measure.line = new google.maps.Polyline({
                map: map,
                clickable: false,
                strokeColor: "#FF0000",
                strokeOpacity: 1,
                strokeWeight: 3,
                path:measure.mvcLine
            });

        }

        // If there is more than two vertexes for a polygon
        if (measure.mvcPolygon.getLength() > 2) {

            // If the polygon hasn't been created yet
            if (!measure.polygon) {

                // Create the polygon (google.maps.Polygon)
                measure.polygon = new google.maps.Polygon({
                    clickable: false,
                    map: map,
                    fillOpacity: 0.25,
                    strokeOpacity: 0,
                    paths: measure.mvcPolygon
                });

            }

        }

    }

    // If there's more than one vertex, measure length, area.
    if (measure.mvcLine.getLength() > 1) {
        measureCalc();
    }

}

function measureCalc() {

    // Use the Google Maps geometry library to measure the length of the line
    var length = google.maps.geometry.spherical.computeLength(measure.line.getPath());
    jQuery("#span-length").text(length.toFixed(1))

    // If we have a polygon (>2 vertexes in the mvcPolygon MVCArray)
    if (measure.mvcPolygon.getLength() > 2) {
        // Use the Google Maps geometry library to measure the area of the polygon
        var area = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
        jQuery("#span-area").text(area.toFixed(1));

         viewUserCreteArea(area);
    }

}

function measureReset() {

    // If we have a polygon or a line, remove them from the map and set null
    if (measure.polygon) {
        measure.polygon.setMap(null);
        measure.polygon = null;
    }
    if (measure.line) {
        measure.line.setMap(null);
        measure.line = null
    }

    // Empty the mvcLine and mvcPolygon MVCArrays
    measure.mvcLine.clear();
    measure.mvcPolygon.clear();

    // Loop through the markers MVCArray and remove each from the map, then empty it
    measure.mvcMarkers.forEach(function(elem, index) {
        elem.setMap(null);
    });
    measure.mvcMarkers.clear();

    jQuery("#span-length,#span-area").text(0);

    $("#useracreId").text(0);
    $("#userroodsId").text(0);
    $("#userperchesId").text(0);
    $("#userhectareId").text(0);

}

//get Color
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '';
    for (var i = 0; i < 8; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}


</script>

<div id="land-registration-module-home-title" class="module-home-title">
    <s:a href="home.do">
        <img src="${pageContext.request.contextPath}/images/interest-party.png" alt="Land Registration">
        <span>
            <s:label value="Full Map"/>
        </span>
    </s:a>
    <div id="back-button" align="right">
        <s:submit type="input" value="%{getText('back.label')}" onclick="goBack();"/>
    </div>
</div>

<h2><s:label value="Land Map"/></h2>

<tr id="kmlFile">
    <td colspan="4">
        <table>
            <tr><p><s:label value="%{getText('length.label')}"/> : <span id="span-length">0</span> m <br>
                <s:label
                        value="%{getText('area_grey_area.label')}"/>: <span
                        id="span-area">0</span> m² - <a href="javascript:measureReset();"><s:label
                        value="%{getText('reset_measure.label')}"/></a></p></tr>
            <tr><s:label value="%{getText('hectare.label')}"/> &nbsp;&nbsp; <s:label id="userhectareId" cssStyle="width: 80px;"/>
                </br>
                <s:label value="%{getText('acre.label')}"/> &nbsp;&nbsp; <s:label id="useracreId" cssStyle="width: 80px;"/> &nbsp;&nbsp;&nbsp;&nbsp;
                <s:label value="%{getText('roods.label')}"/> &nbsp;&nbsp; <s:label id="userroodsId" cssStyle="width: 80px;"/> &nbsp;&nbsp;&nbsp;&nbsp;
                <s:label value="%{getText('perches.label')}"/> &nbsp;&nbsp; <s:label id="userperchesId" cssStyle="width: 80px;"/>
            </tr>
            <tr>
                <td>
                    <div id="map">
                        <%--<s:label value="Land Map"/>--%>
                        <div id='map_canvas' style='height:500px; width: 800px'></div>
                    </div>
                </td>
            </tr>
        </table>
    </td>
</tr>


<s:iterator status="statusMap" value="mapDetailMap">

    <script type="text/javascript">

        if (userRole = 'ORMOI') {
            color = getRandomColor();
        }

    </script>

    <s:iterator status="status" value="value">
        <script type="text/javascript">
            var geo = new Object();
            geo.kmlString = '<s:property  value="kmlString"/>';
            geo.referenceNumber = '<s:property  value="referenceNumber"/>';
            geo.kmlMiddlePoint = '<s:property  value="kmlMiddlePoint"/>';
            geo.kmlLandArea = '<s:property  value="kmlLandArea"/>';
            geo.landName = '<s:property  value="landName"/>';

            if (userRole != 'ORMOI') {
                color = getRandomColor();
            }
            geo.colorCode = color;

            geoData[count++] = geo;
        </script>


    </s:iterator>
</s:iterator>
